package com.ruoyi.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.app.annotation.AppSecurity;
import com.ruoyi.app.util.ReqMsg;
import com.ruoyi.app.util.RspMsg;
import com.ruoyi.bizsys.service.IRealNameAuthLogService;
import com.ruoyi.business.domain.BVNInfo;
import com.ruoyi.business.domain.CreditApplyReq;
import com.ruoyi.business.domain.RealNameReq;
import com.ruoyi.business.service.IAppService;
import com.ruoyi.business.service.ICreditService;
import com.ruoyi.business.service.IRealNameService;
import com.ruoyi.business.service.impl.CreditServiceImpl;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.common.VersionUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.Func;
import com.ruoyi.extdata.service.IExternalApiService;
import com.ruoyi.sms.domain.SmsSendVo;
import com.ruoyi.sms.service.ISmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static com.ruoyi.business.domain.RealNameReq.PRE_COMMIT;
import static com.ruoyi.business.domain.RealNameReq.VERIFY_COMMIT;

/**
 * @Author: Jamnsin
 * @Date: 2021/2/24 9:53 下午
 */
@Slf4j
@Api("授信模块接口")
@RestController
@RequestMapping("/app/credit")
public class CreditController extends BaseController {

    @Autowired
    RedisCache redisCache;

    @Autowired
    ICreditService creditService;

    @Autowired
    ISmsService smsService;

    @Autowired
    IExternalApiService externalApiService;

    @Autowired
    IRealNameAuthLogService realNameAuthLogService;

    @Autowired
    IAppService appService;

    @Autowired
    IRealNameService realNameService;

    @AppSecurity
    @ApiOperation("实名认证")
    @Log(title = "实名认证", businessType = BusinessType.AUTH)
    @PostMapping("/real_name_auth")
    public RspMsg realNameAuth(@Validated @RequestBody ReqMsg reqMsg) {

        //拦截小于2.0.4的版本
        if (VersionUtils.compareVersion(getAppVersion(), "2.0.4") < 0) {
            throw new BusinessException(RspEnmu.APP_VERSION_DONOT_SUPPORT);
        }

        RealNameReq realNameReq = JSON.parseObject(reqMsg.getData().toString(), RealNameReq.class);
        log.info("请求data：{}", JSON.toJSONString(realNameReq));

        if (PRE_COMMIT.equals(realNameReq.getType())) {
            BVNInfo bvnInfo = JSON.parseObject(reqMsg.getData().toString(), BVNInfo.class);
            checkAttribute(bvnInfo);
            bvnInfo.setMiddleName(Optional.ofNullable(bvnInfo.getMiddleName()).orElse(""));
            return RspMsg.ok(creditService.preAuth(bvnInfo, realNameReq.getDeviceInfo()));
        }
        if (VERIFY_COMMIT.equals(realNameReq.getType())) {
            if (Func.hasEmpty(realNameReq.getVerifyCode(), realNameReq.getUuid())) {
                throw new BusinessException(RspEnmu.ILLEGAL_ARGUMENT);
            }

            String phone = redisCache.getCacheObject(BizConstants.REAL_NAME_PHONE + getCustNo());
            SmsSendVo smsVo = SmsSendVo.builder().countryCode(BizConstants.DEFAULT_COUNTRY_CODE).phoneNumber(Func.isEmpty(phone) ? getAppUser().getPhone() : phone).verifyCode(realNameReq.getVerifyCode()).smsType(BizConstants.SMS_TYPE_REAL_NAME_AUTH).uuid(realNameReq.getUuid()).build();
            smsService.verifySmsCode(smsVo);
            realNameService.processRealNameAuth(true);
            return RspMsg.ok(200);
        }
        throw new BusinessException(RspEnmu.ILLEGAL_ARGUMENT);
    }

    @AppSecurity
    @ApiOperation("String，手机号是否一致")
    @Log(title = "校验bvn，手机号是否一致", businessType = BusinessType.AUTH)
    @PostMapping("/real_name_check")
    public RspMsg check(@Validated @RequestBody ReqMsg reqMsg) {

        Map<String, String> map = JSON.parseObject(reqMsg.getData().toString(), HashMap.class);
        String bvn = map.get("bvn");
        String phone = map.get("phone");
        String accountNumber = map.get("accountNumber");
        String fingerprint = map.get("fingerprint");

        if (Func.hasEmpty(phone, fingerprint) || (Func.isEmpty(accountNumber) && Func.isEmpty(bvn))) {
            throw new BusinessException(RspEnmu.ILLEGAL_ARGUMENT);
        }

        JSONObject questionJson = realNameService.verifyPhone(phone, accountNumber, bvn);
        if (Func.isNotEmpty(questionJson.get("unmatch"))) {
            return RspMsg.ok(questionJson);
        }

        //如果校验手机号码 则需要发送验证码
        if (Func.isNotEmpty(phone)) {
            return RspMsg.ok(realNameService.sendSms(phone));
        }
        //只校验bvn 风控校验
        if (!creditService.realNameRiskCheck(fingerprint)) {
            return RspMsg.ok(realNameService.sendSms(null));
        }
        realNameService.processRealNameAuth(true);
        return RspMsg.ok(200);
    }

    @AppSecurity
    @ApiOperation("实名前校验")
    @Log(title = "实名前校验", businessType = BusinessType.GET)
    @PostMapping("/real_name_verify")
    public RspMsg realNameVerify(@RequestBody ReqMsg reqMsg) {
        return RspMsg.ok(realNameService.realNameFailPreCheck(getUserId()) >= 0 ? 200 : 500);
    }

    @AppSecurity
    @ApiOperation("授信申请分步提交")
    @Log(title = "授信申请分步提交", businessType = BusinessType.SUBMIT)
    @PostMapping("/apply")
    public RspMsg creditApply(@RequestBody ReqMsg reqMsg) {
        CreditApplyReq creditApplyReq = JSON.parseObject(reqMsg.getData().toString(), CreditApplyReq.class);
        log.info("请求data：{}", JSON.toJSONString(creditApplyReq));
        checkAttribute(creditApplyReq);
        boolean newVersion = VersionUtils.compareVersion(getAppVersion(), "2.2.8") >= 0;
        creditService.contactCheck(creditApplyReq);
        if(newVersion){
            creditService.processCreditApplyV228(creditApplyReq);
        }else{
            creditService.processCreditApply(creditApplyReq);
        }
        return RspMsg.ok(200);
    }

//    @AppSecurity
//    @RepeatSubmit
//    @ApiOperation("授信申请分步提交")
//    @Log(title = "授信申请分步提交", businessType = BusinessType.SUBMIT)
//    @PostMapping("/v228/apply")
//    public RspMsg creditApplyV228(@RequestBody ReqMsg reqMsg) {
//        CreditApplyReq creditApplyReq = JSON.parseObject(reqMsg.getData().toString(), CreditApplyReq.class);
//        log.info("请求data：{}", JSON.toJSONString(creditApplyReq));
//        checkAttribute(creditApplyReq);
//
//        return RspMsg.ok(200);
//    }


}